/*******************************************************************************
 * @project: Java_Reflect
 * @package: com.burns.java.reflect
 * @file: ReflectTest3.java
 * @author: Administrator
 * @created: 2017年5月13日
 * @purpose:
 * 
 * @version: 1.0
 * 
 * Revision History at the end of file.
 * 
 * Copyright 2017 AcconSys All rights reserved.
 ******************************************************************************/

package com.burns.java.reflect;

import java.lang.reflect.Array;

/**
 * 通过反射机制修改数组的大小
 * 
 * @author Administrator
 *
 */
public class ReflectTest3 {
	public static void main(String[] args) throws Exception {
		int[] temp = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		int[] newTemp = (int[]) arrayInc(temp, 15);
		print(newTemp);
		String[] atr = { "a", "b", "c" };
		String[] str1 = (String[]) arrayInc(atr, 8);
		print(str1);
	}

	// 修改数组大小
	public static Object arrayInc(Object obj, int len) {
		Class<?> arr = obj.getClass().getComponentType();
		Object newArr = Array.newInstance(arr, len);
		int co = Array.getLength(obj);
		System.arraycopy(obj, 0, newArr, 0, co);
		return newArr;
	}

	// 打印
	public static void print(Object obj) {
		Class<?> c = obj.getClass();
		if (!c.isArray()) {
			return;
		}
		System.out.println("数组长度为： " + Array.getLength(obj));
		for (int i = 0; i < Array.getLength(obj); i++) {
			System.out.print(Array.get(obj, i) + " ");
		}
		System.out.println();
	}

}

/**
 * 结果：
 * ------------------------
 * 数组长度为： 15
1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 
数组长度为： 8
a b c null null null null null 

 */

/*******************************************************************************
 * <B>Revision History</B><BR>
 * [type 'revision' and press Alt + / to insert revision block]<BR>
 * 
 * 
 * 
 * Copyright 2017 AcconSys All rights reserved.
 ******************************************************************************/